
package com.yuanmei.model;

import android.util.Log;

import com.yuanmei.common.Utils;

import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Date;

import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

/*
交易日历
    isOpen=1是交易日，isOpen=0为休市
http://file.tushare.org/tsdata/calAll.csv
* */


public class TradeCalenderRealm {
    private static final String TAG = "TradeCalenderRealm";

    private static boolean updateTradeCalenderRealm(Realm realm, String lastCalFile) {
//        String calenderUrl = "http://file.tushare.org/tsdata/calAll.csv";
//        String calenderUrl = "http://129.28.161.203:6880/calAll.csv";
        try {
//            URL request = new URL(calenderUrl);
//            URLConnection connection = request.openConnection();
            InputStreamReader ins = new InputStreamReader(
                    new FileInputStream(lastCalFile), StandardCharsets.UTF_8);
            BufferedReader bufferReader = new BufferedReader(ins);
            bufferReader.readLine(); // skip header
            String line;
            realm.beginTransaction();
            while ((line = bufferReader.readLine()) != null) {
                try {
                    String[] as = line.split(",");
                    String calenderDate = as[2];
                    int isOpen = Integer.parseInt(as[3]);
                    TradeCalender calender = new TradeCalender(calenderDate, isOpen);
                    realm.insertOrUpdate(calender);
                } catch (NumberFormatException e) {
                    Log.w(TAG, "Parse isOpen fail line=" + line, e);
                }
            }
            realm.commitTransaction();
            bufferReader.close();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Update calendar fail, from csv file:" + lastCalFile, e);
        }
        return false;
    }

    public static int checkAndUpdateCalenderRealm(String lastCalFile) {
        int ret;
        RealmConfiguration calenderRealmConfig = new RealmConfiguration.Builder()
                .name("trade_calender.realm")
                .deleteRealmIfMigrationNeeded()
                .build();
        int iDate = Utils.getIDateFromDate(new Date(System.currentTimeMillis()));
        Realm realm = Realm.getInstance(calenderRealmConfig);
        RealmResults<TradeCalender> results = realm.where(TradeCalender.class).equalTo("date", iDate).findAll();
        if (results.size() <= 0) {
            Log.i(TAG, "JKP " + iDate + " query calendar empty, need update by cloud");
            boolean ok = updateTradeCalenderRealm(realm, lastCalFile);
            ret = ok ? 0 : -1;
        } else {
            ret = 1;
        }
        realm.close();
        if (!Realm.compactRealm(calenderRealmConfig)) {
            Log.w(TAG, "Compact calender realm fail");
        }
        return ret;
    }

    public static boolean isCloseDay(Date date) {
        boolean isClose = false; // 没有该日期数据，缺省是开盘
        RealmConfiguration calenderRealmConfig = new RealmConfiguration.Builder()
                .name("trade_calender.realm")
                .deleteRealmIfMigrationNeeded()
                .build();
        int iDate = Utils.getIDateFromDate(date);
        Realm realm = Realm.getInstance(calenderRealmConfig);
        RealmResults<TradeCalender> results = realm.where(TradeCalender.class).equalTo("date", iDate).findAll();
        if (results.size() == 1) {
            TradeCalender calender = results.get(0);
            if (calender != null) {
                isClose = (calender.getIsOpen() != 1);
            }
        }
        realm.close();
        return isClose;
    }

    public static boolean isOpenDate(int iDate) {
        boolean isOpen = true; // 没有该日期数据，缺省是开盘
        RealmConfiguration calenderRealmConfig = new RealmConfiguration.Builder()
                .name("trade_calender.realm")
                .deleteRealmIfMigrationNeeded()
                .build();
        Realm realm = Realm.getInstance(calenderRealmConfig);
        RealmResults<TradeCalender> results = realm.where(TradeCalender.class).equalTo("date", iDate).findAll();
        if (results.size() == 1) {
            TradeCalender calender = results.get(0);
            if (calender != null)
                isOpen = (calender.getIsOpen() == 1);
        }
        realm.close();
        return isOpen;
    }
}
